<template>
  <div class="service-track" v-loading="loading">
    <div class="top-bar">
      <div class="my-btn my-btn-primary mr14" @click="handleEdit">
        <img class="img" :src="edit" alt="" />
        <span>{{ disabled ? '编辑' : '完成编辑' }}</span>
      </div>
    </div>
    <div
      class="form-container"
      :style="{
        height: disabled ? 'calc(100% - 32px)' : 'calc(100% - 90px)'
      }"
    >
      <el-scrollbar class="el-scrollbar-x-hidden">
        <el-form
          class="form"
          ref="form"
          :model="personalInfoForm"
          label-width="auto"
          size="small"
          label-suffix="："
          :disabled="disabled"
        >
          <el-row
            v-for="item in formConfigData.dataItem"
            :key="item.topTitle"
            :gutter="20"
          >
            <div class="top-title">
              <div class="line"></div>
              <div>{{ item.topTitle }}</div>
            </div>
            <template v-for="_item in item.dataSet">
              <!-- 如果是1，则是一行3个 -->
              <el-col
                v-if="
                  getComponentType(_item.componentType) == 1 ||
                  getComponentType(_item.componentType) == 4
                "
                :span="8"
                :key="_item.setKey"
              >
                <el-form-item :label="_item.setName">
                  <ComponentOne
                    :formItem="_item"
                    :forbidEditField="formConfigData.forbidEditField"
                    @change="handleFormChange"
                  ></ComponentOne>
                </el-form-item>
              </el-col>
              <!-- 如果是2，则是一行1个 -->
              <el-col
                v-if="getComponentType(_item.componentType) == 2"
                :span="24"
                :key="_item.setKey"
              >
                <el-form-item :label="_item.setName">
                  <ComponentTwo
                    :formItem="_item"
                    :forbidEditField="formConfigData.forbidEditField"
                    @change="handleFormChange"
                  ></ComponentTwo>
                </el-form-item>
              </el-col>
              <!-- 如果是3，则是table表格 -->
              <el-col
                v-if="getComponentType(_item.componentType) == 3"
                :span="24"
                class="span-spe"
                :key="_item.setKey"
              >
                <el-form-item label-width="0">
                  <ComponentTable
                    :formItem="_item"
                    :forbidEditField="formConfigData.forbidEditField"
                    :disabled="disabled"
                    @change="handleFormChange"
                    :ref="_item.setKey"
                  ></ComponentTable>
                </el-form-item>
              </el-col>
            </template>
          </el-row>
        </el-form>
      </el-scrollbar>
    </div>
    <div class="footer" v-if="!disabled">
      <el-button
        class="btn"
        size="small"
        type="primary"
        plain
        @click="handleCancel"
        >取消</el-button
      >
      <el-button
        class="btn"
        type="primary"
        size="small"
        :loading="saveLoading"
        @click="handleSave"
        >确定</el-button
      >
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import store from '@/store/index';
import { offlineView, offlineEdit } from '@/api';
import utils from '@/utils/treeFormat';
import edit from '@/assets/images/edit.png';
import { componentTypeMap } from '@/utils/dataMap';
import ComponentOne from './ComponentOne';
import ComponentTwo from './ComponentTwo';
import ComponentTable from './ComponentTable';
export default {
  components: {
    ComponentOne,
    ComponentTwo,
    ComponentTable
  },
  props: {
    componentName: {
      type: String,
      default: ''
    },
    selectedRow: {
      type: Object,
      default: () => {}
    },
    configObj: {
      type: Object,
      default: () => {}
    },
    pageConf: {
      type: Object,
      default: () => {}
    }
  },
  computed: {
    ...mapGetters({
      refreshDetailData: 'GET_REFRESH_DETAIL_DATA'
    })
  },
  watch: {
    pageConf: {
      async handler() {
        this.pageConf.columnBtn.forEach((item) => {
          if (item.type === 'edit') {
            this.currentEditValue = item.value;
          }
        });
        await this.offlineViewFn();
      },
      deep: true,
      immediate: true
    },
    refreshDetailData() {
      this.offlineViewFn();
    }
  },
  data() {
    return {
      edit,
      loading: false,
      disabled: true,
      saveLoading: false,
      personalInfoForm: {},
      formConfigData: {},
      specialFormatArrKeys: [],
      currentEditValue: ''
    };
  },
  created() {},
  mounted() {},
  methods: {
    handleFormChange(key, val) {
      const value = JSON.parse(val);
      this.personalInfoForm[key] = this.formatValue(value);
    },
    handleEdit() {
      if (this.disabled) {
        this.disabled = false;
      } else {
        this.handleSave();
      }
    },
    formatValue(value) {
      const type = utils.getType(value);
      // 如果是数组就把数组转成字符串，如果是对象就转成json字符串
      if (type == 'array') {
        return value.join(',');
      } else if (type == 'object') {
        // 如果是空对象，则赋值为空字符串
        if (Object.keys(value).length === 0) {
          return '';
        } else {
          // 如果是有值的对象，则转成json字符串
          return JSON.stringify(value);
        }
      } else if (type == 'null' || type == 'undefined') {
        return '';
      } else {
        return value;
      }
    },
    specialFormatValue(arr) {
      const type = utils.getType(arr);
      if (!arr || (type === 'array' && arr.length === 0)) {
        return '';
      }
      if (type == 'array' && arr.length > 0) {
        return JSON.stringify(arr);
      }
    },
    async handleSave() {
      this.$confirm('确定保存已更改数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.disabled = true;
          this.saveLoading = true;
          let dataSet = [];
          Object.entries(this.personalInfoForm).forEach((item) => {
            // 如果是要进行特殊化处理的值，则进行特殊化处理，例如table表格，因为表格类型的数据传给后台是要json字符串，而是不是逗号连接的字符串
            if (this.specialFormatArrKeys.includes(item[0])) {
              dataSet.push({
                setKey: item[0],
                setValue: this.specialFormatValue(item[1])
              });
            } else {
              dataSet.push({
                setKey: item[0],
                setValue: this.formatValue(item[1])
              });
            }
          });
          const params = {
            cardType: this.selectedRow.cardType,
            personId: this.selectedRow.personId,
            type: 'edit',
            value: this.currentEditValue,
            setCode: this.configObj.setCode,
            dataSet
          };
          const res = await offlineEdit(params);
          this.saveLoading = false;
          if (res.code == 200) {
            this.offlineViewFn();
            this.$message.success('保存成功');
            store.commit('SET_REFRESH_DETAIL_DATA', new Date());
          } else {
            this.$message.error(res.status_desc);
          }
        })
        .catch(() => {});
    },
    handleCancel() {
      this.$confirm('此操作将不保存更改的数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.offlineViewFn();
          this.disabled = true;
        })
        .catch(() => {});
    },
    async offlineViewFn() {
      this.loading = true;
      const params = {
        cardType: this.selectedRow.cardType,
        personId: this.selectedRow.personId,
        setCode: this.configObj.setCode,
        type: 'edit',
        value: this.currentEditValue
      };
      const res = await offlineView(params);
      if (res.code == 200) {
        this.formConfigData = res.data;
        this.formConfigData.dataItem.forEach((item) => {
          item.dataSet.forEach((_item) => {
            // 如果是table表格，则将其塞到特殊格式数组中，以便于后面的编辑接口使用
            if (_item.componentType === 'table') {
              this.specialFormatArrKeys.push(_item.setKey);
              this.specialFormatArrKeys = Array.from(
                new Set(this.specialFormatArrKeys)
              );
            }
            // 获取到所有的初始值
            this.personalInfoForm[_item.setKey] = _item.setValue;
          });
        });
      }
      this.loading = false;
    },
    getComponentType(type) {
      return componentTypeMap[type];
    }
  }
};
</script>

<style lang="scss" scoped>
.service-track {
  height: 100%;
  padding: 12px 0 0 3px;
  position: relative;
  .top-bar {
    display: flex;
    .my-btn {
      display: flex;
      align-items: center;
      font-size: 14px;
      padding: 4px 16px;
      cursor: pointer;
      border-radius: 18px;
      img {
        width: 16px;
        height: 16px;
        margin-right: 5px;
      }
    }
    .my-btn-default {
      border: 1px solid #d2d5e1;
    }
    .my-btn-primary {
      color: #7052ff;
      border: 1px solid #7052ff;
      background: #f2e9ff;
    }
    .mr14 {
      margin-right: 14px;
    }
  }
  .form-container {
    margin-top: 10px;
    .form {
      width: 100%;
      padding: 0 24px 16px 0;
      .top-title {
        font-size: 18px;
        font-weight: 600;
        color: #222;
        margin: 18px 0 18px 0;
        font-family: PingFangSC, PingFang SC;
        display: flex;
        align-items: center;
        .line {
          height: 15px;
          width: 5px;
          background-color: #7052ff;
          border-radius: 5px;
          margin-right: 8px;
          margin-top: 2px;
        }
      }
      .span-spe {
        padding-left: 0 !important;
      }
      ::v-deep .el-row {
        margin: 0 !important;
      }
      ::v-deep .el-date-editor.el-input,
      .el-date-editor.el-input__inner {
        width: 100%;
      }
      ::v-deep .el-col {
        padding: 0 !important;
      }
    }
  }
  .footer {
    display: flex;
    justify-content: center;
    padding-top: 14px;
    border-top: 1px solid #e8e8e8;
    margin-left: -21px;
    .btn {
      width: 200px;
      // margin-right: 12px;
    }
    ::v-deep .el-button--small {
      padding: 11px 15px;
    }
    ::v-deep .el-button--primary.is-plain {
      background-color: #fff;
    }
    ::v-deep .el-button--primary.is-plain:hover,
    .el-button--primary.is-plain:focus {
      color: #7052ff;
    }
  }
}
</style>
